import React, { Children, useEffect, useMemo, useState } from "react";
import './StandingShow.less'
import { Button, Input, message, Select,Table,Tree  } from "antd";
import {RollbackOutlined} from "@ant-design/icons"
import request from "../../../utils/axios";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import type { TreeDataNode, TreeProps } from 'antd';
import { useLocation } from 'react-router-dom'; 
import { useSelector } from "react-redux";

interface StandingType{
    _id:string,
    name:string,
    description:string,
    newTime:string
}

const StandingAdd:React.FC=()=>{
 
  let location = useLocation();  
  const navigate=useNavigate()
  
  // 使用URLSearchParams来解析查询字符串  
  const [search]=useSearchParams()
    const queryParams = new URLSearchParams(location.search);  
    const editId = search.get('editId');  
    const title = search.get('title'); 
  

    const { TextArea } = Input;
    const { Search } = Input;

    const [standingList,setStandingList]=useState<StandingType[]>([])
    const [standingObject,setStandingObject]=useState<any>({})
    const [authorityList,setAuthorityList]=useState([])
    const [name,setName]=useState('')
    const [description,setDescription]=useState('')
    const [refer,setRefer]=useState('')
    const [checkedKeys,setCheckedKeys]=useState<React.Key[]>(['66cf2dcc9b991301baebfcba'])

    const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
    const [defaultExpandAll, setdefaultExpandAll] = useState<boolean>(true);

    const standingName=useSelector((store:any)=>store.counter.standingName)

    //获取身份
    const getstanding=async()=>{
        request.get('getstanding',{_id:editId}).then(error=>{
            console.log(error);
        }).catch(response=>{
            setStandingList(response.data.standingList)
            setStandingObject(response.data.standingList[0])
            setName(response.data.standingList[0].name)
            setDescription(response.data.standingList[0].description)
            setRefer(response.data.standingList[0].refer)
            response.data.standingList[0].authority.forEach((item:any)=>{
                checkedKeys.push(item._id)
                setCheckedKeys(checkedKeys)
            })
        })
    }
    

    //获取权限
    const getauthority=async()=>{
        request.get('getauthority').then(error=>{
            console.log(error);
        }).catch(response=>{
            setAuthorityList(response.data.authorityList)
        })
    }

    //返回新的身份列表
    const newStandingList=useMemo(()=>{
        let list:any=[]
        standingList.forEach((item:any)=>{
            if(item.name!='超级管理员'){
                list.push(item)
            }
        })
        return list
    },[standingList])

    const options=newStandingList.map((item:any)=>{
        return {
            label:item.name,
            value:item._id
        }
    })

    //搜索权限
    const onSearch=()=>{}

    const columns = [
        {
            title: '一级分类',
            dataIndex: 'category1',
            key: 'category1',
        },
        {
            title: '二级分类',
            dataIndex: 'category2',
            key: 'category2',
        },
        {
            title: '三级分类',
            dataIndex: 'category3',
            key: 'category3',
        },
    ];
    const data = authorityList.map((item:any, index) => {
        return {
          key: item._id,
          category1: <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginLeft:'-40px'}}>
                            <input type="checkbox" name="" id="" />
                            <p>{item.label}</p>
                        </div>,
          category2: <div>
                        <input type="checkbox" name="" id="" />
                        <p>{item.children ? item.children.map((childItem:any) => childItem.label).join(' ') : []}</p>
                    </div>,
          category3: <div>
                        <p>
                            {item.children ? item.children.flatMap((childItem:any) => 
                                childItem.children ? childItem.children.map((grandChildItem:any) => grandChildItem.label).join(' ') : []
                            ).join(' ') : []}
                        </p>
                    </div>
        };
    });

    const treeData: TreeDataNode[] = authorityList.map((item:any)=>{
        return  {
                    title: item.label,
                    key: item._id,
                    disabled: item.label=='Dashboard' || standingName!='管理员' && standingName!='超级管理员'?true:false,
                    children: item.children?
                            item.children.map((item2:any)=>{
                                return {
                                    title:item2.label,
                                    key:item2._id,
                                    disabled: item.label=='个人资料' || standingName!='管理员' && standingName!='超级管理员' ?true:false,
                                    children:item2.children?
                                    item2.children.map((item3:any)=>{
                                        return {
                                            title:item3.label,
                                            key:item3._id
                                        }
                                    }):[]
                                }
                            }):[]
                }
    })
    
    const onCheck: TreeProps['onCheck'] = (checkedKeys:any,info) => {
        setCheckedKeys(checkedKeys)
    };    

    //添加身份
    const addstanding=async()=>{
        request.post('addstanding',{
            label:name,
            description:description,
            authority:checkedKeys,
            refer:refer
        }).then(error=>{
            console.log(error);
        }).catch(response=>{
            message.info('添加成功')
            setName('')
            setDescription('')
            setCheckedKeys([])
            setRefer('')
        })
    }
    //编辑身份
    const editstanding=async()=>{
        try {
            await request.put(`editstanding/${editId}`,{label:name,description:description,authority:checkedKeys,refer:refer});
            alert('编辑成功')
        } catch (error) {
            console.error(error);
        }
    }

    const renewal=()=>{
        if(title=='添加身份'){
            addstanding()
        }else if(title=='编辑身份'){
            editstanding()
        }
    }
 

    useEffect(()=>{
        getstanding()
        getauthority()
    },[])

    return (
        <div style={{marginLeft:'15px',marginTop:'10px'}}>
            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
                <p className="wrj-standingadd-p">{title}</p>
                <p style={{color:'gray',cursor:'pointer',marginRight:'20px'}} onClick={()=>{navigate('/app/management')}}><RollbackOutlined style={{marginRight:'5px'}}/>返回</p>
            </div>
            <div className="wrj-standingadd-box">
                <div className="wrj-standingass-input" style={{display:'flex',alignItems:'center'}}>
                    <label>身份名称：</label>
                    <Input placeholder="请输入名称" value={title=='编辑身份'?name:''} onChange={(e)=>{setName(e.target.value)}} style={{width:'25%',height:'35px'}}/>
                    <span style={{marginLeft:'10px'}}>0/20</span>
                </div>
                <div className="wrj-standingass-input">
                    <label>身份描述：</label>
                    <TextArea placeholder="请输入描述" value={title=='编辑身份'?description:''} onChange={(e:any)=>{setDescription(e.target.value)}} rows={5} style={{width:'30%'}}/>
                    <span style={{marginLeft:'10px'}}>0/200(选填)</span>
                </div>
                <div className="wrj-standingass-input" style={{display:'flex',alignItems:'center'}}>
                    <label>参考身份：</label>
                    <Select placeholder="请输入名称" options={options} value={refer} onChange={(e:any)=>{setRefer(e.target.value)}} defaultValue='请选择' style={{width:'25%'}}/>
                    <span style={{marginLeft:'10px'}}>克隆参考身份的权限设置(选填)</span>
                </div>
                <div className="wrj-standingass-input" style={{display:'flex',alignItems:'center'}}>
                    <label>权限设置：</label>
                    <Search placeholder="请输入分类" onSearch={onSearch} style={{ width: '30%' }} />
                </div>
                <Tree 
                    checkable
                    // defaultExpandAll={defaultExpandAll}
                    checkedKeys={title=='编辑身份'?checkedKeys:[]} 
                    onCheck={onCheck} treeData={treeData}
                    autoExpandParent={autoExpandParent}
                    defaultExpandParent={true}
                    className="wrj-standing-tree"
                />
                {
                    title!='查看身份'?
                    <div style={{marginLeft:'100px',marginTop:'50px'}}>
                        <Button style={{marginRight:'20px'}}>取消</Button>
                        <Button type="primary" onClick={renewal}>保存</Button>
                    </div>:''
                }
                {/* <table className="wrj-standingadd-table">
                    <thead style={{height:'35px'}}>
                        <tr>
                            <th className="wrj-standingadd-table-thd" style={{backgroundColor:'#FAFAFA'}}>一级分类</th>
                            <th className="wrj-standingadd-table-thd" style={{backgroundColor:'#FAFAFA'}}>二级分类</th>
                            <th className="wrj-standingadd-table-thd">三级分类</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            authorityList.map((item:any)=>{
                                return <tr>
                                            <td className="wrj-standingadd-table-thd" width={200} style={{backgroundColor:'#FAFAFA'}}>
                                                <input type="checkbox" name="" id="" style={{marginRight:'5px'}}/>
                                                {item.label}
                                            </td>
                                            <td className="wrj-standingadd-table-thd" width={200} style={{backgroundColor:'#FAFAFA'}}>
                                                {
                                                    item.children?
                                                    item.children.map((item2:any)=>{
                                                        return  <p>
                                                                    <input type="checkbox" name="" id="" style={{marginRight:'5px'}}/>
                                                                    {item2.label}
                                                                </p>
                                                    }):[]
                                                }
                                            </td>
                                            <td className="wrj-standingadd-table-thd">
                                                {
                                                    item.children?
                                                    item.children.map((item2:any)=>{
                                                        item2.children?
                                                        item2.children.map((item3:any)=>{
                                                            return  <p>
                                                                        <input type="checkbox" name="" id="" />
                                                                        {item3.label}
                                                                    </p>
                                                        }):[]
                                                    }):[]
                                                }
                                            </td>
                                        </tr>
                            })
                        }
                    </tbody>
                </table> */}
            </div>
        </div>
    )
}

export default StandingAdd
